package com.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.pojo.Employee;
import com.pojo.Kaoqin;
import com.service.EmployeeService;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

	@Autowired
	private EmployeeService employeeService;

	@RequestMapping("/list")
	public String list(Model model) {
		List<Employee> employees = employeeService.GetAllEmployee();
		model.addAttribute("employees", employees);
		return "/jsp/employee";
	}

	@RequestMapping(value = "/toEmployee_add")
	public String toKaoqin_add(Model model) {
		model.addAttribute("employee", new Employee());
		return "/jsp/employee_add";
	}

	@RequestMapping(value = "/employee_add")
	public String Kaoqin_add(@ModelAttribute Employee employee, Model model) {
		String url = "";
		if (employeeService.addEmployee(employee))
			url = "redirect:../employee/list";
		else {
			String error = "添加失败";
			model.addAttribute("employee", employee);
			model.addAttribute("error", error);
			url = "jsp/employee_add";
		}
		return url;
	}
	
	@RequestMapping(value = "/delete")
	public String delete(@RequestParam Integer eid,Model model) {
		String url="";
		System.out.println("删除"+eid);
		if(employeeService.deleteEmployee(eid))
			url= "redirect:../employee/list";
		else {
			String error="删除失败";
			model.addAttribute("error",error);
			url= "redirect:../employee/list";
		}
		return url;
	}
	
	
	@RequestMapping(value = "/toupdate")
	public String toupdate(@RequestParam Integer eid,Model model) {
		model.addAttribute("employee",employeeService.GetEmployee(eid));
		return "/jsp/employee_update";
	}

	@RequestMapping(value = "/update")
	public String update(@ModelAttribute Employee employee ,Model model) {
		String url="";
		System.out.println("更新"+employee);
		if(employeeService.update(employee))
			url= "redirect:../employee/list";
		else {
			String error="删除失败";
			model.addAttribute("error",error);
			url= "redirect:../employee/list";
		}
		return url;
	}
	
	@RequestMapping(value = "/select")
	public String select(@RequestParam Integer id,Model model) {
		List<Employee> emps=new ArrayList<>();
		Employee e=employeeService.GetEmployee(id);
		System.out.println("选择"+e);
		if(e!=null) {
			emps.add(e);
			model.addAttribute("employees", emps);
			return "/jsp/employee";
		}else {
			String error="员工不存在";
			model.addAttribute("error",error);
			model.addAttribute("employees", emps);
			return "/jsp/employee";
		}
	}
}
